Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

116
Vistas
JavaScript: How to better indicate (highlight) current nav page during scroll than just using "scrollY > x"

I currently have a simple webpage layout that is divided in 4 sections (HOME / ABOUT / SKILLS / CONTACT).

Here is my JS code that highlights a specific section from the Nav-bar when a certain pixel amount has been reached during scroll:

let home = document.querySelector(".btn1")
let about = document.querySelector(".btn2")
let skills = document.querySelector(".btn3")
let contact = document.querySelector(".btn4")

function highlight(){
  if(window.scrollY > 1)
  {
    home.classList.add("highlight")
  }

  if(window.scrollY > 550)
  {
    home.classList.remove("highlight")
    about.classList.add("highlight")
  }
  else{
    about.classList.remove("highlight")
  }

  if(window.scrollY > 1210)
  {
    skills.classList.add("highlight")
    about.classList.remove("highlight")
  }
  else{
    skills.classList.remove("highlight")
  }

  if(window.scrollY > 2050)
  {
    contact.classList.add("highlight")
    skills.classList.remove("highlight")
  }
  else{
    contact.classList.remove("highlight")
  }
}

window.addEventListener("scroll", highlight);

This works fine on my 24" monitor, but gets inaccurate if viewport height gets bigger, such as on a 27" monitor.

What better way can I target each page section with scroll?

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

Make a script where you define the elements that you need to reach in order for the state to update (with the use of .offsetTop)

Now the pixels value will dynamically change as the viewport changes.

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda